'use client';

import { useAuth, useClerk } from '@clerk/nextjs';
import { useGateValue, useStatsigClient } from '@statsig/react-bindings';
import clsx from 'clsx';
import { t } from 'i18next';
import { observer } from 'mobx-react-lite';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useIntersectionObserver } from 'usehooks-ts';

import { useStores } from '@/app/(root)/AppProviders';
import Comments from '@/components/comment/Comments';
import ContestSubmissions from '@/components/contest/ContestSubmissions';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import { MobileOnly } from '@/components/responsive/Responsive';
import JoinFriendModal from '@/components/sharing/JoinFriendModal';
import ClipLineageCard from '@/components/song/ClipLineageCard';
import ExtendedFromDropdown from '@/components/song/ExtendedFromDropdown';
import RemixOf from '@/components/song/RemixOf';
import Remixes from '@/components/song/Remixes';
import {
  SunoShortType,
  getSunoShortType,
  tagsToArray,
  tagsToNegativeTags,
} from '@/components/song/songUtils';
import Tabs from '@/components/tab/Tabs';
import LyricsEditable from '@/components/textarea/LyricsEditable';
import TextEditable from '@/components/textarea/TextEditable';
import { useModalContext } from '@/context/ModalContext';
import { usePreviewContext } from '@/context/PreviewContext';
import { useBreakpointMd, useBreakpointXl } from '@/hooks/useBreakpoint';
import { clipHasTerminalStatus, fetchClip } from '@/hooks/useClip';
import { useCommercialRightsSuccessHandler } from '@/hooks/useCommercialRightsSuccessHandler';
import { useAllContestClips } from '@/hooks/useContestClip';
import usePageViewLog from '@/hooks/usePageViewLog';
import useParentClip from '@/hooks/useParentClip';
import { usePlaybarStatusForClip } from '@/hooks/usePlaybar';
import { ContextType } from '@/logging/contextTypes';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip, isDisliked } from '@/state/clipStore';
import { Persona, PersonaMetadata } from '@/state/personaStore';
import { getClipTitle } from '@/utils/clip';
import { getClipDisplayTags } from '@/utils/clip';
import {
  REFERRER_PARAM,
  SIGNUP_SOURCE_PARAM,
  SIGNUP_SOURCE_VALUES,
} from '@/utils/constants';
import { shareClip } from '@/utils/download';
import { eventLogger } from '@/utils/event-logger';
import { ActionName, EventNames } from '@/utils/event-names';
import {
  shouldShowClipLineageCard,
  shouldShowRemixOf,
} from '@/utils/remixUtils';
import { isVideoGenerationFeatureEnabled } from '@/utils/session';
import {
  getClerkSignInRedirectProps,
  getCountString,
  isSecretStatsProfile,
} from '@/utils/utils';

import SongPageHeader from './SongPageHeader';
import SongPageSkeleton from './SongPageSkeleton';

type Props = {
  clip: Clip;
  persona?: PersonaMetadata | Persona | null;
  clipHistoryIds?: string[];
  time?: number;
};

const SONG_PAGE_LOADING_TIMEOUT = 5000;

const DesktopSongPage: React.FC<Props> = observer(
  ({ clip, persona: preloadPersona, clipHistoryIds, time }: Props) => {
    const {
      library,
      clips,
      playbar,
      session,
      menus,
      contest: contestStore,
      queue: queueStore,
      genForm,
    } = useStores();

    const { openModal, openModalWithData } = useModalContext();

    const { setClipForSongRecs, setPreviewClip, setAllowFlushToTop } =
      usePreviewContext();

    const pathname = usePathname();
    const router = useRouter();
    const searchParams = useSearchParams();
    const isMobile = !useBreakpointMd();

    const statsigClient = useStatsigClient();
    const statsigClientLoadingStatus = statsigClient?.client?.loadingStatus;

    const commentCount =
      clips.clipById[clip.id]?.comment_count || clip.comment_count || undefined;

    const showCommentsParam = searchParams.get('show_comments');
    const showComments = showCommentsParam === 'true';
    const commentIdParam = searchParams.get('comment_id');
    const uuidRegex =
      /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;
    const commentId = commentIdParam?.toLowerCase().match(uuidRegex)?.[0];
    const [currentTab, setCurrentTab] = useState<'lyrics' | 'comments'>(
      showComments ? 'comments' : 'lyrics'
    );
    const tabs = useMemo(
      () =>
        [
          { id: 'lyrics', label: t('song.lyrics') } as const,
          {
            id: 'comments',
            label: commentCount
              ? `${t('song.comments')} (${getCountString(commentCount, true)})`
              : t('song.comments'),
          } as const,
        ].filter((tab): tab is Exclude<typeof tab, null> => tab !== null),
      [commentCount]
    );

    const [disliked, setDisliked] = useState(false);
    const [clipTitle, setClipTitle] = useState(getClipTitle(clip));
    const [newClipTitle, setNewClipTitle] = useState(clipTitle);
    // Derive clipImageUrl from MobX store for real-time updates
    const clipImageUrl = clips.clipById[clip.id]?.image_url || clip.image_url;
    const [upvoteCount, setUpvoteCount] = useState(clip?.upvote_count);
    const [lyrics, setLyrics] = useState(clip.metadata?.prompt || '');

    const [isCoverEnabled, setIsCoverEnabled] = useState(false);

    usePageViewLog({
      actionName: 'PageViewed',
      componentContext: 'song',
      principalObjectType: 'clip',
      principalObjectValue: clip.id,
      context: { created_by: clip.user_id ?? '' },
    });

    // Handle commercial rights purchase success
    useCommercialRightsSuccessHandler({ clip, menus });

    useEffect(() => {
      const loadClip = async () => {
        try {
          const fetchedClip = await fetchClip(clips, clip.id, true);
          if (clipHasTerminalStatus(fetchedClip)) {
            clips.updateClips([fetchedClip]);
            clip = fetchedClip;
            return;
          }
          const interval = setInterval(async () => {
            try {
              const fetchedClip = await fetchClip(clips, clip.id, true);
              clips.updateClips([fetchedClip]);
            } catch (error) {
              console.error('Error fetching clip during interval:', error);
            }
          }, 1000);

          return () => clearInterval(interval);
        } catch (error) {
          console.error('Error loading clip:', error);
        }
      };

      loadClip();
    }, [clip, clips]);

    useEffect(() => {
      if (!session || !clips || !clip) return;

      if (clip.metadata?.cover_clip_id) {
        setIsCoverEnabled(true);
        return;
      }

      const checkFeature = async () => {
        const isContestClip = await contestStore.isCoverEnabledOrIsContest(
          clip.id,
          clip.user_id ?? ''
        );
        setIsCoverEnabled(isContestClip);
      };

      checkFeature();
    }, [session, clip.id, clips]);

    useEffect(() => {
      setTimeout(() => {
        setLoading(false);
      }, SONG_PAGE_LOADING_TIMEOUT);
    }, []);

    useEffect(() => {
      setDisliked(isDisliked(clip));
    }, [clip]);

    useEffect(() => {
      setUpvoteCount(clips.clipById[clip.id]?.upvote_count);
    }, [clips.clipById[clip.id]?.upvote_count]);

    const { isSignedIn } = useAuth();
    const clerk = useClerk();

    const handleDislikeClick = () => {
      logWebUserEvent({
        actionName: 'DislikeSongOnSongPageClicked',
        context: {
          clipId: clip.id,
          version: 'v1',
        },
      });
      if (!isSignedIn) {
        clerk.openSignIn({
          withSignUp: true,
          ...getClerkSignInRedirectProps(`/song/${clip.id}`, {
            [REFERRER_PARAM]: pathname,
            [SIGNUP_SOURCE_PARAM]: SIGNUP_SOURCE_VALUES.SONG_PAGE,
          }),
        });
      } else {
        clips.dislikeClip(clip?.id, !disliked);
        eventLogger.logAudioActionEvent(
          !isTablet,
          disliked ? ActionName.undoDislikeSong : ActionName.undoDislikeSong,
          clip,
          session,
          pathname
        );
        setDisliked(!disliked);
      }
    };

    const [isFollowing, setIsFollowing] = useState<boolean>(false);
    useEffect(() => {
      clips.updateClips([clip]);
      setIsFollowing(clip?.is_following_creator === true);
    }, [clip]);

    useEffect(() => {
      const storedClipTitle = getClipTitle(clips.clipById[clip.id]);
      if (storedClipTitle !== clipTitle) {
        setClipTitle(storedClipTitle);
        setNewClipTitle(storedClipTitle);
      }
      setDisliked(isDisliked(clips.clipById[clip.id]));
    }, [clips.clipById[clip.id]?.title, clips.clipById[clip.id]?.reaction]);

    useEffect(() => {
      if (!playbar.clip) {
        queueStore.setPlayContext({
          clips: [clip],
          contextType: ContextType.Song,
          contextId: clip.id,
        });
        playbar.clip = clip;
        playbar.setNoClipPlayCallback(() => {
          playbar.playClip(clip, null, null, false, undefined);
        });
        playbar.setIsClipPreloaded(true);
      }
      setClipForSongRecs(clip);
      setAllowFlushToTop(true);
      setPreviewClip(null);
      return () => {
        setClipForSongRecs(null);
        setAllowFlushToTop(false);
      };
    }, [clip]);

    useEffect(() => {
      if (time && playbar.duration) {
        const normalizedTime = time && time >= playbar.duration ? 0 : time;
        logWebUserEvent({
          actionName: 'TimestampURLLoaded',
          context: { timestamp: normalizedTime },
        });
        playbar.userSetCurrentProgressWithTime(normalizedTime);
        playbar.setNoClipPlayCallback(() => {
          playbar.playClip(clip, null, null, false, normalizedTime);
        });
      }
    }, [time, playbar.duration]);

    const isTablet = useBreakpointMd();
    const isDesktop = useBreakpointXl();

    const [loading, setLoading] = useState(true);

    // Song page does not aggressively check the playback context
    const { isCurrentSong, isPlaying } = usePlaybarStatusForClip(clip.id);
    const isTrashed = clips.clipById[clip.id]?.is_trashed ?? false;

    const showTwoColummLayout = isDesktop;
    const showTabLayout = tabs.length > 1 && !showTwoColummLayout;

    useEffect(() => {
      if (isTablet !== undefined && statsigClientLoadingStatus !== 'Loading') {
        setLoading(false);
      }
    }, [isTablet, statsigClientLoadingStatus]);

    const handleFollow = async () => {
      logWebUserEvent({
        actionName: 'FollowArtistOnSongPageClicked',
        context: {
          clipId: clip.id,
          artistId: clip.user_id || undefined,
          version: 'v1',
        },
      });
      if (!isSignedIn) {
        clerk.openSignIn({
          withSignUp: true,
          ...getClerkSignInRedirectProps(`/song/${clip.id}`, {
            [REFERRER_PARAM]: pathname,
            [SIGNUP_SOURCE_PARAM]: SIGNUP_SOURCE_VALUES.SONG_PAGE,
          }),
        });
      } else {
        eventLogger.segmentTrack(EventNames.artistActionEvent, {
          isMobile: false,
          userId: session.user?.id,
          followeeId: clip?.user_id,
          actionName: isFollowing
            ? ActionName.unfollowArtist
            : ActionName.followArtist,
          clickSourceUrl: pathname,
        });
        await library.apiClient.POST('/api/profiles/follow', {
          body: {
            unfollow: isFollowing,
            handle: clip.handle || '',
          },
        });
        setIsFollowing(!isFollowing);
      }
    };

    // Use the clip from MobX store to get real-time updates (e.g., when video cover changes)
    const currentClip = clips.clipById[clip.id] || clip;
    const sunoShortType = getSunoShortType(currentClip);
    const isSunoShort =
      sunoShortType == SunoShortType.VIDEO &&
      currentClip.metadata?.video_to_song_video_upload_url;
    const isVideoCover = currentClip.video_cover_url;
    const videoUrl = isSunoShort
      ? currentClip.metadata?.video_to_song_video_upload_url || undefined
      : isVideoCover
        ? currentClip.video_cover_url || undefined
        : undefined;

    const handleTogglePlay = () => {
      if (isCurrentSong && !playbar.isClipPreloaded) {
        playbar.togglePlay();
        return;
      }
      queueStore.setPlayContext({
        currentIndex: 0,
        clips: queueStore.getClipsForContext(ContextType.Song, clip.id),
        contextType: ContextType.Song,
        contextId: clip.id,
      });
      playbar.playClip(clip);
    };

    const enableOmniplayer = useGateValue('web-omniplayer');
    const contestGate = useGateValue('contest-hub-song-pages');

    // Contest functionality
    const { data: allContestsData } = useAllContestClips();

    // Check if this song is a remix base (part of any contest's base clips)
    const isRemixBase = useMemo(() => {
      if (!allContestsData?.contests) return false;

      return allContestsData.contests.some((contest: any) =>
        contest.base_clip_ids?.includes(clip.id)
      );
    }, [allContestsData, clip.id]);

    const handleImageClick = () => {
      if (enableOmniplayer) {
        openModal(ModalTypes.OMNIPLAYER);
      }
      handleTogglePlay();
    };

    const visibleStats = !isSecretStatsProfile({ handle: clip?.handle || '' });
    const showHistoryClips =
      clipHistoryIds &&
      clipHistoryIds.length > 0 &&
      session.user?.id === clip.user_id;
    const hasLineageClips =
      !!(clip.metadata?.cover_clip_id && isCoverEnabled) ||
      !!clip.metadata?.upsample_clip_id ||
      showHistoryClips;

    const updateTitle = useCallback(
      async (title: string) => {
        if (clip.title === title) return;
        const clipId = clip.id;
        const result = await clips.setMetadata({
          clipId,
          title,
        });
        if (result) {
          if (result.success) {
            clip.title = title;
            setClipTitle(title);
            setNewClipTitle(title);
            eventLogger.logAudioActionEvent(
              false,
              ActionName.editTitle,
              clip,
              session,
              pathname
            );
          } else {
            setNewClipTitle(clipTitle);
          }
        }
      },
      [clip, clipTitle, clips, pathname, session]
    );

    const [videoUrls, setVideoUrls] = useState<any[]>([]);
    useEffect(() => {
      // Only call video generation API if the feature is enabled
      if (isVideoGenerationFeatureEnabled(session)) {
        clips.getGeneratedVideos(clip.id).then((videoUrls: string[]) => {
          setVideoUrls(videoUrls);
        });
      }
    }, [clip, session]);

    const renderTitleContent = useCallback(
      ({ children: value }: { children?: string }) => {
        return clip.user_id !== session.userId ? (
          <h1 className='w-full border-b-2 border-transparent font-serif text-[40px]/[56px] font-light text-foreground-primary'>
            {value}
          </h1>
        ) : (
          <TextEditable
            key='editableTitle'
            className='w-full font-serif text-[40px]/[56px] font-light text-foreground-primary'
            value={value}
            onValueChange={setNewClipTitle}
            onValueCommit={updateTitle}
            disabled={clip.user_id !== session.userId}
          />
        );
      },
      [clip.user_id, session.userId, updateTitle]
    );

    // `isIntersecting: false` means that we've scrolled past the header
    const { ref: headerRef, isIntersecting } = useIntersectionObserver();
    const [header, setHeader] = useState<HTMLDivElement | null>(null);
    const getHeaderRef = useCallback(
      (node: HTMLDivElement | null) => {
        setHeader(node);
        headerRef(node);
      },
      [headerRef]
    );

    const persona = preloadPersona || clip.persona;

    const { parentClip } = useParentClip({ clipId: clip.id });
    const contestsData = allContestsData;

    const handleRemixContestRemixClick = useCallback(
      ({ isFromMobileButton = false }: { isFromMobileButton: boolean }) => {
        if (!parentClip) {
          return;
        }
        // Analytics: Track remix contest button clicks
        // SongPageHeaderRemixContestButtonClicked = Mobile users clicking remix button in header component
        // SongPageRemixOfContestButtonClicked = Desktop/tablet users clicking remix button (non-mobile)
        logWebUserEvent({
          actionName: isFromMobileButton
            ? 'SongPageHeaderRemixContestButtonClicked'
            : 'SongPageRemixOfContestButtonClicked',
          context: {
            clipId: clip.id,
            parentClipId: parentClip.id || '',
          },
        });
        router.push(`/remix?song_id=${parentClip.id}`);
        if (isMobile) {
          genForm.shouldOpenMobileCreate = true;
        }
      },
      [clip, parentClip, isMobile, genForm]
    );

    // Difference: handleRemixContestRemixClick remixes the parent clip (when current song is already a remix),
    // while handleContestSubmissionRemixClick finds and remixes the contest base clip directly (when current song is a contest submission)
    const handleContestSubmissionRemixClick = useCallback(
      ({ isFromMobileButton = false }: { isFromMobileButton: boolean }) => {
        // Get contest IDs from submission
        const contestIds = clip.metadata?.contest_ids || [];
        if (contestIds.length === 0) return;

        // Find relevant contest and get first base clip ID
        const relevantContest = contestsData?.contests?.find((contest) =>
          contestIds.includes(contest.id)
        );

        const baseClipId = relevantContest?.base_clip_ids?.[0];
        if (!baseClipId) return;

        // Analytics: Track remix contest button clicks
        // SongPageHeaderRemixContestButtonClicked = Mobile users clicking remix button in header component
        // SongPageRemixOfContestButtonClicked = Desktop/tablet users clicking remix button (non-mobile)
        logWebUserEvent({
          actionName: isFromMobileButton
            ? 'SongPageHeaderRemixContestButtonClicked'
            : 'SongPageRemixOfContestButtonClicked',
          context: {
            clipId: clip.id,
            parentClipId: baseClipId,
          },
        });
        router.push(`/remix?song_id=${baseClipId}`);
        if (isMobile) {
          genForm.shouldOpenMobileCreate = true;
        }
      },
      [clip, contestsData, isMobile, genForm, router]
    );

    const handleRemixClick = useCallback(() => {
      logWebUserEvent({
        actionName: 'SongPageHeaderRemixButtonClicked',
        context: {
          clipId: clip.id,
        },
      });
      router.push(`/remix?song_id=${clip.id}`);
      if (isMobile) {
        genForm.shouldOpenMobileCreate = true;
      }
    }, [clip.id, router, isMobile, genForm]);

    const handleAnimateCoverClick = useCallback(() => {
      openModalWithData(
        ModalTypes.GENERATE_COVER_ART,
        { clipId: clip.id, useClipCoverImage: true },
        'DesktopSongPage'
      );
    }, [clip.id, openModalWithData]);

    return loading ? (
      <SongPageSkeleton />
    ) : (
      <div className='flex h-full w-full flex-col items-stretch overflow-y-scroll bg-background-primary md:px-4'>
        <JoinFriendModal clipId={clip.id} hideOnMobileWebRedirect={true} />
        <SongPageHeader
          ref={getHeaderRef}
          className='pb-8 max-md:flex-col md:pt-8'
          imageClassName={clsx(
            'max-md:w-full max-md:aspect-square max-md:min-h-[360px] max-md:rounded-none max-md:-mb-44',
            'max-md:after:block max-md:after:h-64 after:from-background-primary'
          )}
          contentClassName='max-md:px-4'
          title={newClipTitle}
          avatarImageUrl={clip.avatar_image_url || undefined}
          handle={clip.handle || undefined}
          displayName={clip.display_name || undefined}
          {...(persona?.is_public
            ? {
                personaId: persona.id || undefined,
                personaImageUrl: persona.image_s3_id || undefined,
                personaDisplayName: persona.name || undefined,
                personaUserAvatarImageUrl: persona.user_image_url || undefined,
                personaUserHandle: persona.user_handle || undefined,
                personaUserDisplayName: persona.user_display_name || undefined,
              }
            : undefined)}
          videoUrl={videoUrl}
          imageUrl={clipImageUrl || undefined}
          tags={[
            ...tagsToArray(getClipDisplayTags(clip)),
            ...tagsToNegativeTags(
              tagsToArray(clip.metadata?.negative_tags || '')
            ),
          ]}
          caption={clip.caption || undefined}
          isSongOwner={!!(session.userId && session.userId === clip.user_id)}
          clip={clip}
          id={clip.id}
          createdAt={clip.created_at}
          clipType={clip.metadata?.type}
          modelMajorVersion={clip.major_model_version}
          modelName={clip.model_name}
          playCount={visibleStats ? clip.play_count : undefined}
          commentCount={visibleStats ? commentCount : undefined}
          likeCount={visibleStats ? upvoteCount : undefined}
          dislikeCount={undefined}
          titleContent={renderTitleContent}
          isFollowing={isFollowing}
          isDisliked={disliked}
          isCurrentSong={isCurrentSong}
          isTrashed={isTrashed}
          isPlaying={isPlaying}
          isRemixBase={isRemixBase}
          onImageClick={handleImageClick}
          onRemixClick={handleRemixClick}
          onFollowClick={
            clip.user_id !== session.user?.id ? handleFollow : undefined
          }
          onPlayCountClick={() => {
            if (isCurrentSong && !playbar.isClipPreloaded) {
              playbar.togglePlay();
              return;
            }
            queueStore.setPlayContext({
              currentIndex: 0,
              clips: queueStore.getClipsForContext(ContextType.Song, clip.id),
              contextType: ContextType.Song,
              contextId: clip.id,
            });
            playbar.playClip(clip);
          }}
          onCommentClick={() => {
            logWebUserEvent({
              actionName: 'CommentsOnSongPageClicked',
              context: {
                clipId: clip.id,
                numComments: commentCount,
                version: 'v1',
              },
            });
            setCurrentTab('comments');
          }}
          onDislikeClick={handleDislikeClick}
          onAddToPlaylistClick={() => {
            menus.setSelected(new Set([clip.id]));
            openModal(ModalTypes.ADD_TO_PLAYLIST, 'DesktopSongPage');
            logWebUserEvent({
              actionName: 'AddToPlaylistOnSongPageClicked',
              context: {
                clipId: clip.id,
                version: 'v1',
              },
            });
          }}
          onShareClick={async () => {
            await shareClip(clips.apiClient, clip);
            logWebUserEvent({
              actionName: 'ShareSongOnSongPageClicked',
              context: {
                isMobile: !isTablet,
                version: 'v1',
              },
            });
          }}
          onPlayClick={() => {
            logWebUserEvent({
              actionName: 'PlayCTAOnSongPageClicked',
              context: {
                clipId: clip.id,
                version: 'v1',
              },
            });
            if (isCurrentSong && !playbar.isClipPreloaded) {
              playbar.togglePlay();
              return;
            }
            queueStore.setPlayContext({
              currentIndex: 0,
              clips: queueStore.getClipsForContext(ContextType.Song, clip.id),
              contextType: ContextType.Song,
              contextId: clip.id,
            });
            playbar.playClip(clip);
          }}
          onRemixContestClick={
            parentClip?.user_handle
              ? handleRemixContestRemixClick
              : handleContestSubmissionRemixClick
          }
          onAnimateCoverClick={handleAnimateCoverClick}
        >
          <>
            <div
              className={clsx(
                'flex w-full flex-col gap-2 md:flex-row lg:flex-col xl:flex-row',
                { hidden: !hasLineageClips }
              )}
            >
              {clip.metadata?.speed_clip_id &&
                shouldShowClipLineageCard(clip, parentClip, session) && (
                  <div className='flex-1 overflow-hidden md:max-w-[220px]'>
                    <ClipLineageCard
                      clipId={clip.metadata.speed_clip_id}
                      label='Adjusted Speed of'
                      contextId={clip.id}
                      contextType={ContextType.SongReferencedClip}
                    />
                  </div>
                )}
              {clip.metadata?.cover_clip_id &&
                isCoverEnabled &&
                shouldShowClipLineageCard(clip, parentClip, session) && (
                  <div className='flex-1 overflow-hidden md:max-w-[220px]'>
                    <ClipLineageCard
                      label='Cover of'
                      compact={true}
                      clipId={clip.metadata?.cover_clip_id}
                      contextId={clip.id}
                      contextType={ContextType.SongReferencedClip}
                    />
                  </div>
                )}
              {clip.metadata?.upsample_clip_id && (
                <div className='flex-1 overflow-hidden md:max-w-[220px]'>
                  <ClipLineageCard
                    label='Remaster of'
                    compact={true}
                    clipId={clip.metadata?.upsample_clip_id}
                    contextId={clip.id}
                    contextType={ContextType.SongReferencedClip}
                  />
                </div>
              )}
              {showHistoryClips &&
                clip.metadata?.task !== 'gen_stem' &&
                shouldShowClipLineageCard(clip, parentClip, session) && (
                  <div className='w-full flex-1 md:max-w-[220px]'>
                    <ExtendedFromDropdown
                      clipHistoryIds={clipHistoryIds}
                      contextId={clip.id}
                      contextType={ContextType.SongReferencedClip}
                    />
                  </div>
                )}
              {clip.metadata?.task === 'gen_stem' &&
                clip.metadata.stem_from_id &&
                shouldShowClipLineageCard(clip, parentClip, session) && (
                  <ClipLineageCard
                    label='Stemmed from'
                    clipId={clip.metadata.stem_from_id}
                    contextId={clip.id}
                    contextType={ContextType.SongReferencedClip}
                  />
                )}
              {clip.metadata?.underpainting_clip_id &&
                shouldShowClipLineageCard(clip, parentClip, session) && (
                  <ClipLineageCard
                    label='Vocals from'
                    clipId={clip.metadata.underpainting_clip_id}
                    contextId={clip.id}
                    contextType={ContextType.SongReferencedClip}
                  />
                )}
              {clip.metadata?.overpainting_clip_id &&
                shouldShowClipLineageCard(clip, parentClip, session) && (
                  <ClipLineageCard
                    label='Instrumental from'
                    clipId={clip.metadata.overpainting_clip_id}
                    contextId={clip.id}
                    contextType={ContextType.SongReferencedClip}
                  />
                )}
            </div>
            {parentClip?.user_handle &&
              shouldShowRemixOf(clip, parentClip, session) && (
                <div className='w-fit min-w-[220px] pt-2'>
                  <RemixOf
                    parentClip={parentClip}
                    contextId={clip.id}
                    contextType={ContextType.SongReferencedClip}
                    onRemixContestRemixClick={handleRemixContestRemixClick}
                  />
                </div>
              )}
          </>
        </SongPageHeader>
        <div
          className={clsx('w-full flex-1 px-6 pb-48 md:px-0', {
            'flex flex-col': showTabLayout,
          })}
        >
          {isVideoGenerationFeatureEnabled(session) && (
            <div className='min-w-0 flex-1'>
              {videoUrls.map((videoUrl) => (
                <div key={videoUrl}>
                  <video controls width='500px' src={videoUrl}></video>
                </div>
              ))}
            </div>
          )}

          {/* Contest Remix Submissions - Above Lyrics/Comments */}
          {contestGate && (
            <div className='mb-6'>
              <ContestSubmissions
                baseClipId={clip.id}
                contextClipId={clip.id}
                clipId={clip.id}
                title='Remix Submissions'
                showCta={false}
                location='song-page'
                titleClassName='text-[24px] leading-[32px] md:text-[24px] md:leading-[32px]'
                containerClassName='mt-[24px]'
              />
            </div>
          )}

          {showTabLayout && (
            <Tabs
              className='pb-4'
              textClass='px-3 py-2 min-w-0 text-sm'
              tabs={tabs}
              onTabClick={(index) => {
                setCurrentTab(tabs[index].id);
                if (tabs[index].id === 'comments') {
                  logWebUserEvent({
                    actionName: 'CommentsOnSongPageClicked',
                    context: {
                      clipId: clip.id,
                      numComments: commentCount,
                      version: 'v1',
                    },
                  });
                }
                if (tabs[index].id === 'lyrics') {
                  logWebUserEvent({
                    actionName: 'LyricsOnSongPageClicked',
                    context: {
                      clipId: clip.id,
                      version: 'v1',
                    },
                  });
                }
              }}
              selectedIndex={Math.max(
                0,
                tabs.findIndex(({ id }) => id === currentTab)
              )}
            />
          )}
          <div
            className={clsx({
              'flex flex-row gap-4': showTwoColummLayout,
            })}
          >
            <div
              className={clsx({
                hidden: showTabLayout && currentTab !== 'lyrics',
                'min-w-0 flex-1': showTwoColummLayout,
              })}
            >
              <LyricsEditable
                lyrics={lyrics}
                setLyrics={setLyrics}
                promptLimit={7500}
                onBlur={async (prompt: string) => {
                  if (prompt === clip.metadata.prompt) return;
                  const clipId = clip.id;
                  const model_name = clip.model_name;
                  const result = await clips.setClipPrompt(
                    clipId,
                    prompt,
                    model_name
                  );
                  if (result && result.success) {
                    clip.metadata.prompt = prompt || '';
                    setLyrics(prompt);
                    eventLogger.logAudioActionEvent(
                      false,
                      ActionName.editLyrics,
                      clip,
                      session,
                      pathname
                    );
                  } else {
                    setLyrics(clip.metadata.prompt || '');
                  }
                }}
                disabled={
                  clip.user_id !== session.userId ||
                  clip.preview_seconds !== undefined
                }
              />
            </div>

            <Comments
              entityId={clip.id}
              entityType='clip'
              allowComments={
                clips.clipById[clip.id].allow_comments &&
                clip.preview_seconds === undefined
              }
              numComments={commentCount}
              className={clsx({
                hidden: showTabLayout && currentTab !== 'comments',
                'flex-1 self-start rounded-4xl': showTwoColummLayout,
                'sticky top-10 -mb-12': showTwoColummLayout,
              })}
              headerClassName={clsx({
                'pt-4 bg-(--comment-bg) rounded-t-[inherit]':
                  showTwoColummLayout,
              })}
              bodyClassName={clsx({
                'max-h-[max(210px,calc(100svh-74px-2.5rem-12rem-var(--comment-header-height,0)))]':
                  showTwoColummLayout,
                'transition-[max-height] duration-500 ease-out':
                  showTwoColummLayout,
                'pb-4 bg-(--comment-bg) rounded-b-[inherit] overflow-y-auto':
                  showTwoColummLayout,
              })}
              style={
                showTwoColummLayout
                  ? // Container style
                    ({
                      '--comment-bg': 'var(--color-background-secondary)',
                      '--comment-input-bg': 'var(--color-background-tertiary)',
                      '--skeleton-bg': 'var(--color-background-tertiary)',
                      '--song-page-header-height': `max(calc(300px + 4rem), ${header?.offsetHeight ?? 0}px)`,
                      '--comment-header-height': isIntersecting
                        ? 'var(--song-page-header-height)' // poster height + padding
                        : '2.5rem', // padding
                    } as React.CSSProperties)
                  : undefined
              }
              isUserContentOwner={
                session.userId !== undefined && clip.user_id === session.userId
              }
              autoFocus={showComments}
              deeplinkedCommentId={commentId || undefined}
            />
          </div>

          <MobileOnly>
            <Remixes clip={clip} />
          </MobileOnly>
        </div>
      </div>
    );
  }
);

export default DesktopSongPage;
